import { Component } from 'react';
import Taro, { Config, getCurrentInstance } from '@tarojs/taro';
import { View ,Input} from '@tarojs/components'
import { AtList, AtListItem, AtButton, AtMessage} from "taro-ui"
import { connect } from 'react-redux'
import { carInfo } from '@/store/car/action'
import KeyBoard from './keyboard'
import CarModel from './model'
import classnames from 'classnames'
import './index.scss'
import { fetchAdd, fetchUpdate } from '@/api/car'
import { addCustomer } from '@/api/distribution'

const INPUT_NUM: number = 8 // 车牌号输入框个数
const SELETE_INDEX_FIRST: number = 0
const EmptyArray = new Array(INPUT_NUM).fill('') // ['','','','','','','','']

type State = {
		form:string,
    type: number // 2为编辑
    mode: number
    isOpenedKeyboard: boolean
    isOpenedCarModel: boolean
    isDefault: boolean
    selectIndex: number
    carNumArr: Array<string>
    carModel: carModelType
    params: any,
		mobile:any,
		distributionLeaderId:any
};
type carModelType = {
    selector: object | null
    ids: Array<number | string>
    modelId: string | number | null
    jekunModelCode?: any
    title: string
}
type selectMode = 0 | 1
type SelectIndex = -1 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7

@connect<any>(({ car }) => ({ car }), _dispatch => ({
    dispatchFetchList() {
      return _dispatch(carInfo())
    }
}))
export default class UserInfo extends Component<any, State> {
    $instance = getCurrentInstance();
    /**
     * 指定config的类型声明为: Taro.Config
     *
     * 由于 typescript 对于 object 类型推导只能推出 Key 的基本类型
     * 对于像 navigationBarTextStyle: 'black' 这样的推导出的类型是 string
     * 提示和声明 navigationBarTextStyle: 'black' | 'white' 类型冲突, 需要显示声明类型
     */
    config: Config = {
        navigationBarTitleText: '',
        navigationBarTextStyle: 'black',
        navigationBarBackgroundColor: '#fff'
    }
    constructor(props) {
        super(props)
        this.state = {
						form:'default',
						distributionLeaderId:'',
						mobile:'',
						// form:'distribution',
            type: 1,
            mode: 0,
            carModel: {
                selector: null,
                ids: [],
                modelId: null,
                jekunModelCode: null,
                title: '请选择车型'
            },
            isDefault: false,
            isOpenedKeyboard: false,
            isOpenedCarModel: false,
            selectIndex: -1,
            carNumArr: EmptyArray,
            params: ''
        }

    }
    componentMount() {

    }
    componentDidMount() {
			let { form,distributionLeaderId  } =  this.$instance.router.params
			this.setState({
				form:form || 'default',
				distributionLeaderId :distributionLeaderId  || ''
			},()=>{
				this.chooseViewType()
			})
    }
    chooseViewType() {
        const { params } = this.$instance.router
        // console.log('params', params)
        if (params.type === '2') {
            Taro.setNavigationBarTitle({
                title: '编辑车辆'
            })
            this.setDefault(params)
        } else {
						if(this.state.form == 'distribution'){
							Taro.setNavigationBarTitle({
								title: '添加客户'
							})
						}else{
							Taro.setNavigationBarTitle({
									title: '添加爱车'
							})
							// this.handleClick(0)
							this.handleSelectModel()
						}
        }
    }
		pushRank=(arr, len)=>{
			if (arr.length < len) {
				arr.push('')
				return this.pushRank(arr, len)
			} else {
					return arr
			}
		}
    setDefault=(obj) =>{
			let params = {
				...obj,
				brandName:decodeURI(obj.brandName),
				carLicense:decodeURI(obj.carLicense),
				carModelFullName:decodeURI(obj.carModelFullName),
				modelName:decodeURI(obj.modelName),
				seriesName:decodeURI(obj.modelName)
			}
			let aaa = decodeURI(obj.modelName)
			console.log('obj.modelName',aaa)
			console.log('decodeURIobj.modelName',decodeURIComponent(obj.modelName))
				console.log('setDefault')
				console.log('obj',obj)
				console.log('params',params)
        let paramsLincens = params.carLicense.split('')
        let { carNumArr } = this.state
				console.log('this',this)

        let len = carNumArr.length
        let newCarNumArr = this.pushRank(paramsLincens, len)
				console.log('newCarNumArr',newCarNumArr)
        this.setState({
            carNumArr: newCarNumArr,
            carModel: {
                selector: {
                    ids: [params.brandId, params.seriesId, params.modelId],
                    brand: {
                        id: params.brandId,
                        text: params.brandName
                    },
                    series: {
                        id: params.seriesId,
                        text: params.seriesName
                    },
                    model: {
                        id: params.modelId,
                        jekunModelCode: params.jekunModelCode,
                        text: params.modelName
                    },
                    inputText: params.carModelFullName
                },
                ids: [params.brandId, params.seriesId, params.modelId],
                modelId: params.modelId,
                jekunModelCode: params.jekunModelCode,
                title: params.carModelFullName
            },
            type: 2,
            params
        })
    }
    handleCloseBoard(e) {
        this.setState({
            isOpenedKeyboard: false,
            isOpenedCarModel: false,
            selectIndex: -1
        })

    }
    proviceSelect(key) {

        const { selectIndex, carNumArr } = this.state
        let newArr = carNumArr.map((item, index) => {
            if (selectIndex === index) {
                item = key
            }
            return item
        })

        let index = selectIndex !== carNumArr.length - 1 ? selectIndex + 1 : selectIndex
        // console.log('proviceSelect', carNumArr, key, newArr, selectIndex)
        let filterNewArr = newArr.filter( i => i !== '')
        let lastIndex = 7

        this.setState({
            carNumArr: newArr
        }, () => {
            let str = this.state.carNumArr.join('')
            if (!str) {
                this.setSelectState(0, 0)
            }
        })
        if (index === 0) {
            this.setSelectState(0, 0)
        } else {
            this.setSelectState(1, index)
        }
        if (filterNewArr.length === 8 && selectIndex === lastIndex) {
            this.setState({
                isOpenedKeyboard: false
            })
        }
    }
    modelSelect(selector) {
        this.setState({
            isOpenedCarModel: false,
            carModel: {
                selector,
                ids: selector.ids,
                modelId: selector.model.id,
                jekunModelCode: selector.model.jekunModelCode,
                title: selector.inputText
            }
        })
    }
    keyboardDel() {
        const { selectIndex, carNumArr } = this.state
        if (selectIndex === SELETE_INDEX_FIRST && carNumArr[selectIndex] === '') return
        let activeIndex = (selectIndex === carNumArr.length -1 || selectIndex === SELETE_INDEX_FIRST) && carNumArr[selectIndex] !== '' ? selectIndex : selectIndex - 1
        carNumArr[activeIndex] = ''
        this.setState({
            carNumArr,
            selectIndex: activeIndex
        }, () => {
            if (this.state.selectIndex === SELETE_INDEX_FIRST) {
                this.setSelectState(0, 0)
            }
        })
    }

    handleClick(index: SelectIndex) {
        const { carNumArr } = this.state
        let activeIndex = 0
        let keyboardMode: 0 | 1 = 1
        if (carNumArr[0] === '') {
            activeIndex = 0
            keyboardMode = 0
        } else if (carNumArr[1] === '') {
            activeIndex = 1
        } else if (carNumArr[2] === '') {
            activeIndex = 2
        } else if (carNumArr[3] === '') {
            activeIndex = 3
        } else if (carNumArr[4] === '') {
            activeIndex = 4
        } else if (carNumArr[5] === '') {
            activeIndex = 5
        } else if (carNumArr[6] === '') {
            activeIndex = 6
        } else if (carNumArr[7] === '') {
            activeIndex = 7
        } else {
            activeIndex = 7
        }
        this.setSelectState(keyboardMode, activeIndex)
    }
    setSelectState(mode: selectMode, index) {
        this.setState({
            mode,
            isOpenedKeyboard: true,
            selectIndex: index,
            isOpenedCarModel: false
        })
    }
    handleSelectModel() {
			console.log('点击了吗----')
        this.setSelectState(0, -1)
        this.setState({
            isOpenedCarModel: true,
            isOpenedKeyboard: false
        })
    }

    handleInputChange(e){
        this.setState({
            mobile:e.detail.value
        })
    }

    /**
    * 车险团长添加客户
    **/
    async addCustomer() {
        const { carModel, carNumArr, mobile,distributionLeaderId} = this.state
        console.log('carNumArr',carNumArr)
        let valid = true
        if (!mobile) {
            Taro.showToast({
                icon: 'none',
                title: '手机号不能为空',
                duration: 2000
            })
            return
        }
        if (!/\d{11}/gi.test(mobile)) {
            Taro.showToast({
                icon: 'none',
                title: '检查手机号是否正确！',
                duration: 2000
            })
            return
        }
        carNumArr.map( (item, index) => {
            if (index < 7 && !item) {
                    Taro.atMessage({
                            'message': '车牌填写有误',
                            'type': 'warning'
                        })
                    valid = false
            }else if(index>1 && ['O','I','o','i'].includes(item)){
							Taro.atMessage({
								'message': '车牌序号不能使用字母I和O',
								'type': 'warning'
							})
							valid = false
					}
        })
        if (!carModel.jekunModelCode) {
                Taro.atMessage({
                        'message': '请选择车型',
                        'type': 'warning'
                })
                valid = false
        }
        if (valid) {
            Taro.showLoading({
                title: '加载中...',
                mask: true
            })
            addCustomer({
                carLicense:carNumArr.join('').trim(),
                mobile,
                jekunModelCode:carModel.jekunModelCode
            }).then(res=>{
                let {customerUserId,carLicense} = res.data.data
                console.log('res',res)
                console.log('distributionLeaderId',distributionLeaderId)
                const query: any = {
                    customerUserId,
                    carLicense,
                    distributionLeaderId
                }
                let path:string = ''
                if(distributionLeaderId){ // 买保险
                    path = `/insurance/index`
                    Taro.redirectTo({
                        url:`/pages/webview/index/index?path=${path}&query=${JSON.stringify(query)}`
                    })
                }else{
                    path = `/distribution/customer`
                    Taro.navigateBack()
                }
            }).finally(()=>{
                Taro.hideLoading()
            })
        }
}

    async handleSave() {
        const { carModel, carNumArr, isDefault, params} = this.state
        let valid = true
				console.log('carNumArr',carNumArr)
        carNumArr.map( (item, index) => {
            if (index < 7 && !item) {
                Taro.atMessage({
                    'message': '车牌填写有误',
                    'type': 'warning'
                  })
                valid = false
            }else if(index>1 && ['O','I','o','i'].includes(item)){
								Taro.atMessage({
									'message': '车牌序号不能使用字母I和O',
									'type': 'warning'
								})
								valid = false
						}
        })
        // console.log('carModel.jekunModelCode', carModel.jekunModelCode)
        if (!carModel.jekunModelCode) {
            Taro.atMessage({
                'message': '请选择车型',
                'type': 'warning'
            })
            valid = false
        }
        if (valid) {
            let is_update = '2'
            let carLicenseStr = carNumArr.join('').trim()
            let postParams = {
                carLicense: carLicenseStr,
                jekunModelCode: carModel.jekunModelCode
            }
            if (params.type === is_update && params.jekunModelCode === carModel.jekunModelCode && !!Number(params.isDefault) === isDefault && params.carLicense === carLicenseStr) {
                Taro.navigateBack({
                    delta: 1,
                })
                return
            }
            if (params.type === is_update) {
                postParams['id'] = params.id
                if (params.jekunModelCode === carModel.jekunModelCode && params.carLicense === carLicenseStr) {
                    await this.props.dispatchFetchList()
                    Taro.navigateBack({
                        delta: 1,
                    })
                    return
                }
                this.handleUpdate(postParams)
            } else {
                this.handleAdd(postParams)
            }

        }
    }
    async handleAdd(postParams) {
        try {
            let res = await fetchAdd(postParams)
            if (!res.data.success) {
                throw Error(res.data.message)
            }
            await this.props.dispatchFetchList()
            Taro.navigateBack({
                delta: 1,
            })

        } catch (error) {
            Taro.atMessage({
                'message': error.message,
                'type': 'warning'
            })
        }
    }
    async handleUpdate(postParams) {

        try {
            let res = await fetchUpdate(postParams)
            if (!res.data.success) throw Error(res.data.msg)
console.log('有没有迅')
            await this.props.dispatchFetchList()
            Taro.navigateBack({
                delta: 1,
            })
        } catch (error) {
console.log('error',error)
        }
    }
    render() {
        const { mode, isOpenedKeyboard, isOpenedCarModel, selectIndex, carNumArr, carModel,form ,distributionLeaderId } = this.state
        return (

            <View className='add-car'>
                <View className='add-car-wrap'>
                    <View className='hidden-board' onClick={this.handleCloseBoard.bind(this)}></View>
										{
											form == 'distribution' ? (
												<View className="phone">
												<View className="phone-key">手机号</View>
												<Input placeholder="请输入" maxLength={11} className="phone-val"
												value={this.state.mobile}
												onInput={(e)=>this.handleInputChange(e)}></Input>
										</View>
											):null
										}

                    <View className='license flex-column'>
                        <View className='license-wrap flex-row'>
                            <View className='dotted'></View>
                            {carNumArr.map((key, index) =>
                                <View
                                  key={String(index)}
                                  onClick={this.handleClick.bind(this, index)}
                                  className={
                                        classnames('provice', 'item', {
                                            'active-input': selectIndex === index
                                        })
                                    }
                                >
                                    {key}
                                </View>
                            )}
                        </View>
                    </View>
                    <View className='car-model'>
                        <AtList hasBorder={false}>
                            <AtListItem onClick={this.handleSelectModel.bind(this)} hasBorder={false} title={carModel.title} arrow='right' />
                        </AtList>
                    </View>

										{
												!!distributionLeaderId ? (
												<View className='distribution-tips'>
													<View className="tips">温馨提示：请提前准备相关资料</View>
													<View className="tips">车辆所有权属于个人：车主姓名、身份证号、身份证正反面、地址、身份证有效期</View>
													<View className="tips">车辆所有权属于企业：营业执照、单位名称、统一信用代码、单位地址、证件有效期</View>
												</View>
												):null
										}

										{
											form != 'distribution' ? (
												<View className='btn'>
														<AtButton type='primary' onClick={this.handleSave.bind(this)}>保存</AtButton>
												</View>
											) : (
												<View className='btn'>
														<AtButton type='primary' onClick={this.addCustomer.bind(this)}>提交</AtButton>
												</View>
											)
										}


                </View>
                <KeyBoard mode={mode} isOpened={isOpenedKeyboard} onChange={this.proviceSelect.bind(this)} onDelete={this.keyboardDel.bind(this)} />
                { isOpenedCarModel && <CarModel isOpened={isOpenedCarModel} model={carModel.selector} onChange={this.modelSelect.bind(this)}></CarModel> }
                <AtMessage />
            </View>
        )
    }
}
